package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName SecurityConfig
 * @Description
 * @Author hhwu
 * @Date 2022/5/31 10:02
 * Version 1.0
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {
    @Override
    public void configure(WebSecurity web) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 忽略对静态资源的访问
         * @Date 10:08 2022/5/31
         * @Param [web]
         * @return void
         **/
        web.ignoring().antMatchers("/resources/**");
    }

//    因为我们要用自己之前定义过的认证方式，因此就废弃了security提供的
    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        *//**
         * @Author hhwu
         * @Description //TODO 定义认证类型
         * @Date 10:10 2022/5/31
         * @Param [auth]
         * @return void
         **//*
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 授权，主要是梳理controller下的每一个路径
         * TODO 将用户类型和权限进行关联的方法：UserService.getAuthorities()
         * @Date 10:09 2022/5/31
         * @Param [http]
         * @return void
         **/
        // 这些路径只有指定权限才能访问，其他路径均可访问
        http.authorizeRequests()

                //登录就能访问的路径
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        AUTHORITY_USER,
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR
                )

                // 版主才有的权限
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )

                // 管理员才有的权限
                .antMatchers(
                        "/discuss/delete",
                        "/data/**",
                        "/actuator/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )

                .anyRequest().permitAll()
                .and().csrf().disable();// 禁用csrf

        // 不可访问时的处理方式
        http.exceptionHandling()
                // 未认证时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String xRequestWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestWith)) {// 异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "您还没有登录！"));
                        } else {// 同步请求
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                // 权限不足时的处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestWith)) {// 异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "您没有访问此功能的权限！"));
                        } else {// 同步请求
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }

                    }
                });
        // security底层默认自动拦截/logout请求，进行退出处理。
        // 覆盖他默认的逻辑，才能执行我们的退出代码
        http.logout().logoutUrl("/securitylogout");// 指定一个无效的界面即可，此时就不做处理，就进入我们自己的退出逻辑
    }
}
